package com.sxfq.loansupermarket.backsystem.modular.marketing.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ReturnVisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchReturnVisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.IReturnVisitService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.SearchReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 预约回访信息
 *
 * @author
 * @Date
 */
@Controller
@RequestMapping("/reservationRevisit")
public class ReservationsVisitController extends BaseController {

    @Autowired
    IReturnVisitService service;

    @Autowired
    IConsultantService consultantService;

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    IReservationsService reservationsService;

    private String PREFIX = "/returnVisit/";


    /**
     * 预约客户管理列表
     */
    @RequestMapping("/list1")
    @ResponseBody
    public Object RecordInfoList(SearchReturnVisitInfo info, HttpServletRequest request) {
        Page<ReturnVisitInfo> page = new PageFactory<ReturnVisitInfo>().defaultPage();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        try {
            List<ReturnVisitInfo> list = new ArrayList<ReturnVisitInfo>();
            list = service.selectPageListByQuery(page, info);
            if (list.size() == 0) {
                page.setCurrent(1);
                list = service.selectPageListByQuery(page, info);
            }
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 统计查询 预约回访 人数
     */
    @RequestMapping(value = "/totalNum",method = RequestMethod.POST)
    @ResponseBody
    public List<ReservationsInfo> totalNum(String param1, String param2, String param3, String param4) throws Exception {
        String reservationsInfo = "";
        String listHuifangTime = "left(substring_index(a.huifang,',<b>',LENGTH(huifang) - LENGTH(huifang)-1),19)";
        if (StringUtils.isNotBlank(param1)) {
            reservationsInfo += " and a.huifang like CONCAT('%', '" + param1 + "','%') ";
        }
        if (StringUtils.isNotBlank(param2)) {
            reservationsInfo += " and a.follower ='" + param2 + "'";
        }
        if (StringUtils.isNotBlank(param3)) {
            reservationsInfo += " and "+listHuifangTime+" >='" + param3 + "'";
        }
        if (StringUtils.isNotBlank(param4)) {
            reservationsInfo += " and "+listHuifangTime+" <='" + param4 + "'";
        }
        String sql = "select count(*) as countNum  from reservations_info a where 1=1   " + reservationsInfo;
        List<ReservationsInfo> infoList = sqlMapper.selectList(sql, ReservationsInfo.class);
        return infoList;
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/reservationRevisitExport")
    public void reservationsExportt(
                                   @RequestParam(required = false) String follower,
                                   @RequestParam(required = false) String startRevisitTime,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String endTime, HttpServletResponse response) {
        try {
            SearchReturnVisitInfo searchInfo = new SearchReturnVisitInfo();
            searchInfo.setStartRevisitTime(startRevisitTime);
            searchInfo.setStartTime(startTime);
            searchInfo.setEndTime(endTime);
            searchInfo.setFollower(follower);
            List<ReturnVisitInfo> list = service.reservationsExportt(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
//            if("1".equals(pageType)){
            for (int i = 0; i < 13; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("电话号码");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("到店状态");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("回访状态");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("一级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("回访内容");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("跟进人");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("建档人");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("建档时间");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("预约时间");
            cell.setCellStyle(style);

            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                ReturnVisitInfo map = list.get(i);
                row = sheet.createRow(i + 1);

                String customerName = map.getCustomerName();
                String customerPhone = map.getCustomerPhone();
                String  status = map.getStatus();
                String  statuss = map.getStatuss();
                String  oneChannel =map.getOneChannel();
                String sex = map.getSex();
                int customerAge = 0;
                if (map.getCustomerAge() != null) {
                    customerAge = map.getCustomerAge();
                }
                String huifang = map.getHuifang();
                String archiving = map.getArchiving();
                follower = map.getFollower();
                String filingTime = map.getFilingTime();
                String appointmentTime =map.getAppointmentTime();

                String id = map.getId();
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 11; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(customerName);
                row.getCell(1).setCellValue(customerPhone);
                row.getCell(2).setCellValue(status);
                row.getCell(3).setCellValue(statuss);
                row.getCell(4).setCellValue(oneChannel);
                row.getCell(5).setCellValue(sex);
                row.getCell(6).setCellValue(customerAge);
                row.getCell(7).setCellValue(huifang);
                row.getCell(8).setCellValue(archiving);
                row.getCell(9).setCellValue(follower);
                row.getCell(10).setCellValue(filingTime);
                row.getCell(11).setCellValue(appointmentTime);
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }

}
